package com.tai.cobrapp.database;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import com.tai.cobrapp.model.DetalleRelevamiento;
import com.tai.cobrapp.model.Dispositivo;
import com.tai.cobrapp.model.Establecimiento;
import com.tai.cobrapp.model.Relevamiento;
import com.tai.cobrapp.model.Usuario;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper 
{	 	
	private final static String DATABASE_NAME_USR_TABLE = "Usuarios";
	private final static String DATABASE_CREATE_USR_TABLE_STATEMENT = "CREATE TABLE "+ DATABASE_NAME_USR_TABLE +"(id INTEGER PRIMARY KEY AUTOINCREMENT, user VARCHAR, password VARCHAR, active INTEGER)";
	
	private final static String DATABASE_NAME_ESTABLECIMIENTOS_TABLE = "Establecimientos";
	private final static String DATABASE_CREATE_ESTABLECIMIENTOS_TABLE_STATEMENT = "CREATE TABLE "+ DATABASE_NAME_ESTABLECIMIENTOS_TABLE +"(id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, description TEXT, active INTEGER)";
	
	private final static String DATABASE_NAME_DISPOSITIVOS_TABLE = "Dispositivos";
	private final static String DATABASE_CREATE_DISPOSITIVOS_TABLE_STATEMENT = "CREATE TABLE "+ DATABASE_NAME_DISPOSITIVOS_TABLE +"(id INTEGER PRIMARY KEY AUTOINCREMENT, idEstablecimiento INTEGER, name VARCHAR, description TEXT, active INTEGER)";
	
	private final static String DATABASE_NAME_RELEVAMIENTOS_TABLE = "Relevamientos";
	private final static String DATABASE_CREATE_RELEVAMIENTOS_TABLE_STATEMENT = "CREATE TABLE "+ DATABASE_NAME_RELEVAMIENTOS_TABLE +"(id INTEGER PRIMARY KEY AUTOINCREMENT, idUser INTEGER, name VARCHAR, dateUpdated NUMERIC, montoTotal REAL, active INTEGER)";

	private final static String DATABASE_NAME_DETALLES_RELEVAMIENTOS_TABLE = "DetallesRelevamiento";
	private final static String DATABASE_CREATE_DETALLES_RELEVAMIENTOS_TABLE_STATEMENT = "CREATE TABLE "+ DATABASE_NAME_DETALLES_RELEVAMIENTOS_TABLE +"(id INTEGER PRIMARY KEY AUTOINCREMENT," +
						"idRelevamiento INTEGER, idDispositivo INTEGER, montoUnitario REAL, vendido INTEGER, turnoManiana INTEGER, turnoTarde INTEGER, active INTEGER)";
	
    private final static String DATABASE_NAME = "CobrAppDatabase";
    private final static String DATABASE_DROP_STATEMENT = "DROP TABLE IF EXISTS " + DATABASE_NAME;    
    private Context context;
    private static DatabaseHelper databaseInstance;
    
    
    public static DatabaseHelper getDatabaseInstance(Context context)
    {
    	if(databaseInstance == null)
    	{
    		databaseInstance = new DatabaseHelper(context.getApplicationContext());
    	}
    	return databaseInstance;
    }
    
    public DatabaseHelper(Context context, String name, CursorFactory factory, int version) 
    {
        super(context, name, factory, version);      
        this.context = context;
    }
    
    public DatabaseHelper(Context context)
    {
    	super(context, DATABASE_NAME, null, 1);    	
    }
 
    @Override
    public void onCreate(SQLiteDatabase db) 
    {       	
    	db.execSQL(DATABASE_CREATE_USR_TABLE_STATEMENT);
    	db.execSQL(DATABASE_CREATE_ESTABLECIMIENTOS_TABLE_STATEMENT);
    	db.execSQL(DATABASE_CREATE_DISPOSITIVOS_TABLE_STATEMENT);
    	db.execSQL(DATABASE_CREATE_RELEVAMIENTOS_TABLE_STATEMENT);
    	db.execSQL(DATABASE_CREATE_DETALLES_RELEVAMIENTOS_TABLE_STATEMENT);
    }
 
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    {      
        db.execSQL(DATABASE_DROP_STATEMENT); 
        db.execSQL(DATABASE_CREATE_USR_TABLE_STATEMENT);
        db.execSQL(DATABASE_CREATE_ESTABLECIMIENTOS_TABLE_STATEMENT);
        db.execSQL(DATABASE_CREATE_DISPOSITIVOS_TABLE_STATEMENT);
        db.execSQL(DATABASE_CREATE_RELEVAMIENTOS_TABLE_STATEMENT);
    	db.execSQL(DATABASE_CREATE_DETALLES_RELEVAMIENTOS_TABLE_STATEMENT);
    }    
    
    public Boolean databaseExists()
    {
    	if(SQLiteDatabase.openDatabase(context.getDatabasePath(DATABASE_NAME).getPath(), null, 0) != null)
    	{
    		this.close();
    		return true;
    	}
    	
    	return false;    			
    }
    /* METODOS PARA USUARIO */
    public Boolean existeUsuario(Editable u){
    	int flag = 0; //flag 0 => usuario no existe, flag 1 => usuario existe
    	Cursor cursor = null;
    	cursor = getReadableDatabase().query(DATABASE_NAME_USR_TABLE, null, null, null, null, null, null);
    	String usuario = u.toString();
    	
    	while(cursor.moveToNext()){
    		if(usuario.equals(cursor.getString(cursor.getColumnIndex("user")))){
    			flag = 1;
    		}
    	}
    	this.close();
    	if(flag == 1){
    		return true;
    	}else{
    		return false;
    	}
    }
    
    
    public void insertarUsuario(Usuario u)
    {	
    	ContentValues values = new ContentValues();
    	Editable nombreUsuario = u.getUsername();
    	Editable passUsuario = u.getPassword();    	
    	
    	values.put("user", nombreUsuario.toString());
    	values.put("password", passUsuario.toString());
    	values.put("active", 1);
    	
    	getWritableDatabase().insert(DATABASE_NAME_USR_TABLE, null, values);
    	this.close();
    }
    
    public Integer validacionUsuario(Editable u, Editable p){
    	//int flag = 0; //flag 0 => usuario no existe, flag 1 => usuario existe
    	Cursor cursor = null;
    	int idUser = -1;
    	// String[] column = new String[] {"user", "email"};
    	// String[] args = new String[] {"user1"};
    	// cursor = getReadableDatabase().query(DATABASE_NAME_USR_TABLE, column, "user=?", args, null, null, null);
    	// la query con todos los parametros en null es como un SELECT *
    	cursor = getReadableDatabase().query(DATABASE_NAME_USR_TABLE, null, null, null, null, null, null);
    	String usuario = u.toString();
    	String password = p.toString();
    	
    	while(cursor.moveToNext()){
    		if(usuario.equals(cursor.getString(cursor.getColumnIndex("user"))) && password.equals(cursor.getString(cursor.getColumnIndex("password")))){
    			idUser = cursor.getInt(cursor.getColumnIndex("id"));
    			//flag = 1;
    		}
    	}
    	this.close();
    	return idUser;
    }
    public String getUserPass(Editable u){
    	Cursor cursor = null;
    	
    	cursor = getReadableDatabase().query(DATABASE_NAME_USR_TABLE, null, null, null, null, null, null);
    	String usuario = u.toString();
    	String password = "";
    	while(cursor.moveToNext()){
    		if(usuario.equals(cursor.getString(cursor.getColumnIndex("user"))) ){
    			password = cursor.getString(cursor.getColumnIndex("password"));
    			//flag = 1;
    		}
    	}
    	this.close();
    	return password;
    }
    /* FIN METODOS PARA USUARIO */
//    
//    public void getNews()
//    {
//    	Cursor cursor = null;
//    	
//    	cursor = getReadableDatabase().query(DATABASE_NAME_USR_TABLE, null, null, null, null, null, null);
//    	while(cursor.moveToNext())
//    	{
//    		Log.d("NOTICIA: ", cursor.getString(cursor.getColumnIndex("noticia_titulo")));
//    	}
//    	this.close();
//    }
    /* METODOS PARA ESTABLECIMIENTO */
    public Boolean existeEstablecimiento(Editable name){
    	int flag = 0; //flag 0 => no existe, flag 1 => existe
    	Cursor cursor = null;
    	
    	cursor = getReadableDatabase().query(DATABASE_NAME_ESTABLECIMIENTOS_TABLE, null, null, null, null, null, null);
    	   	
    	String establecimiento = name.toString();
    	
    	while(cursor.moveToNext()){
    		if(establecimiento.equals(cursor.getString(cursor.getColumnIndex("name")))){
    			flag = 1;
    		}
    	}
    	this.close();
    	if(flag == 1){
    		return true;
    	}else{
    		return false;
    	}
    }
    public Boolean existeOtroEstablecimiento(Editable baseName, Editable name){
    	// Busqueda coincidencias que no sean con el nombre base, el cual quiero editar o dejar como esta
    	int flag = 0; //flag 0 => no existe, flag 1 => existe
    	Cursor cursor = null;
    	
    	cursor = getReadableDatabase().query(DATABASE_NAME_ESTABLECIMIENTOS_TABLE, null, null, null, null, null, null);
    	   	
    	String establecimiento = name.toString();
    	
    	while(cursor.moveToNext()){
    		if(!baseName.toString().equals(cursor.getString(cursor.getColumnIndex("name")))){
    			if(establecimiento.equals(cursor.getString(cursor.getColumnIndex("name")))){
    				flag = 1;
    			}
    		}
    	}
    	this.close();
    	if(flag == 1){
    		return true;
    	}else{
    		return false;
    	}
    }
    
    public void insertarEstablecimiento(Establecimiento estb)
    {	
    	ContentValues values = new ContentValues();
    	Editable name = estb.getName();
    	Editable description = estb.getDescription();
    	
    	values.put("name", name.toString());
    	values.put("description", description.toString());
    	values.put("active", 1);
    	//Log.d("Name Establ", name.toString());
    	//Log.d("Desc Establ", description.toString());
    	getWritableDatabase().insert(DATABASE_NAME_ESTABLECIMIENTOS_TABLE, null, values);
    	this.close();
    }
    public ArrayList<Establecimiento> ListEstablecimientos(Integer option)
    {
    	Cursor cursor = null;
    	ArrayList<Establecimiento> ListEstab = new ArrayList<Establecimiento>();
    	cursor = getReadableDatabase().query(DATABASE_NAME_ESTABLECIMIENTOS_TABLE, null, null, null, null, null, null);
    	while(cursor.moveToNext())
    	{
    		//if(cursor.getInt(cursor.getColumnIndex("active")) != 0){
    			Editable name = new SpannableStringBuilder(cursor.getString(cursor.getColumnIndex("name")));
    			Editable desc = new SpannableStringBuilder(cursor.getString(cursor.getColumnIndex("description")));
    			Integer id = cursor.getInt(cursor.getColumnIndex("id"));
    			Boolean active = cursor.getInt(cursor.getColumnIndex("active")) == 1? true:false;
    			ListEstab.add(new Establecimiento(id,name,desc, active));
    			Log.d("Estblecimiento: ", cursor.getString(cursor.getColumnIndex("name")));
    		//}
    	}
    	this.close();
    	return ListEstab;
	}
    public ArrayList<Establecimiento> ListActiveEstablecimientos(Integer option)
    {
    	Cursor cursor = null;
    	ArrayList<Establecimiento> ListEstab = new ArrayList<Establecimiento>();
    	cursor = getReadableDatabase().query(DATABASE_NAME_ESTABLECIMIENTOS_TABLE, null, null, null, null, null, null);
    	while(cursor.moveToNext())
    	{
    		if(cursor.getInt(cursor.getColumnIndex("active")) != 0){
    			Editable name = new SpannableStringBuilder(cursor.getString(cursor.getColumnIndex("name")));
    			Editable desc = new SpannableStringBuilder(cursor.getString(cursor.getColumnIndex("description")));
    			Integer id = cursor.getInt(cursor.getColumnIndex("id"));
    			Boolean active = cursor.getInt(cursor.getColumnIndex("active")) == 1? true:false;
    			ListEstab.add(new Establecimiento(id,name,desc, active));
    			Log.d("Estblecimiento: ", cursor.getString(cursor.getColumnIndex("name")));
    		}
    	}
    	this.close();
    	return ListEstab;
	}
    public Boolean HayEstablecimientos()
    {
    	Cursor cursor = null;
    	cursor = getReadableDatabase().query(DATABASE_NAME_ESTABLECIMIENTOS_TABLE, null, null, null, null, null, null);
    	while(cursor.moveToNext())
    	{
    		//if(cursor.getInt(cursor.getColumnIndex("active")) != 0){
    			return true;
    		//}
    	}
    	return false;
    	//this.close();
	}
    public Boolean HayEstablecimientosActivos()
    {
    	Cursor cursor = null;
    	cursor = getReadableDatabase().query(DATABASE_NAME_ESTABLECIMIENTOS_TABLE, null, null, null, null, null, null);
    	while(cursor.moveToNext())
    	{
    		if(cursor.getInt(cursor.getColumnIndex("active")) != 0){
    			return true;
    		}
    	}
    	return false;
    	//this.close();
	}
    public Integer getIdEstablecimiento(String name){
    	Cursor cursor = null;
    	
    	cursor = getReadableDatabase().query(DATABASE_NAME_ESTABLECIMIENTOS_TABLE, null, null, null, null, null, null);
    	   	
    	String establecimiento = name.toString();
    	
    	while(cursor.moveToNext()){
    		if(establecimiento.equals(cursor.getString(cursor.getColumnIndex("name")))){
    			return cursor.getInt(cursor.getColumnIndex("id"));
    		}
    	}
    	this.close();
    	return -1;
    }
    public void ActualizarEstablecimiento(Establecimiento establishment){
    	String strFilter = "id=" + establishment.getId();
    	ContentValues args = new ContentValues();
    	args.put("active", establishment.isActive()?1:0);
    	args.put("description", establishment.getDescription().toString());
    	args.put("name", establishment.getName().toString());
    	// agregar otros datos a actualizar
    	getReadableDatabase().update(DATABASE_NAME_ESTABLECIMIENTOS_TABLE, args, strFilter, null);
    }
    /* FIN METODOS PARA ESTABLECIMIENTO */
    /* METODOS PARA DIPOSITIVO */
    public Boolean existeDispositivo(Editable name){
    	int flag = 0; //flag 0 => no existe, flag 1 => existe
    	Cursor cursor = null;
    	
    	cursor = getReadableDatabase().query(DATABASE_NAME_DISPOSITIVOS_TABLE, null, null, null, null, null, null);
    	   	
    	String establecimiento = name.toString();
    	
    	while(cursor.moveToNext()){
    		if(establecimiento.equals(cursor.getString(cursor.getColumnIndex("name")))){
    			flag = 1;
    		}
    	}
    	this.close();
    	if(flag == 1){
    		return true;
    	}else{
    		return false;
    	}
    }
    public Boolean existeOtroDispositivo(Editable baseName, Editable name){
    	int flag = 0; //flag 0 => no existe, flag 1 => existe
    	Cursor cursor = null;
    	
    	cursor = getReadableDatabase().query(DATABASE_NAME_DISPOSITIVOS_TABLE, null, null, null, null, null, null);
    	   	
    	String establecimiento = name.toString();
    	
    	while(cursor.moveToNext()){
    		if(!baseName.toString().equals(cursor.getString(cursor.getColumnIndex("name")))){
    			if(establecimiento.equals(cursor.getString(cursor.getColumnIndex("name")))){
    				flag = 1;
    			}
    		}
    	}
    	this.close();
    	if(flag == 1){
    		return true;
    	}else{
    		return false;
    	}
    }
    public void insertarDispositivo(Dispositivo disp)
    {	
    	ContentValues values = new ContentValues();
    	Editable name = disp.getName();
    	Editable description = disp.getDescription();
    	Integer idEstabl = disp.getIdEstablecimiento();
    	
    	values.put("name", name.toString());
    	values.put("description", description.toString());
    	values.put("idEstablecimiento", idEstabl);
    	values.put("active", 1);
    	//Log.d("Name Establ", name.toString());
    	//Log.d("Desc Establ", description.toString());
    	getWritableDatabase().insert(DATABASE_NAME_DISPOSITIVOS_TABLE, null, values);
    	this.close();
    }
    public ArrayList<Dispositivo> ListDispositivos()
    {
    	Cursor cursor = null;
    	ArrayList<Dispositivo> ListDisp = new ArrayList<Dispositivo>();
    	cursor = getReadableDatabase().query(DATABASE_NAME_DISPOSITIVOS_TABLE, null, null, null, null, null, null);
    	while(cursor.moveToNext())
    	{
    		//if(cursor.getInt(cursor.getColumnIndex("active")) != 0){
    			Editable name = new SpannableStringBuilder(cursor.getString(cursor.getColumnIndex("name")));
    			Editable desc = new SpannableStringBuilder(cursor.getString(cursor.getColumnIndex("description")));
    			Integer id = cursor.getInt(cursor.getColumnIndex("id"));
    			Integer idEst = cursor.getInt(cursor.getColumnIndex("idEstablecimiento"));
    			ListDisp.add(new Dispositivo(id,idEst,name,desc));
    			//Log.d("Estblecimiento: ", cursor.getString(cursor.getColumnIndex("name")));
    		//}
    	}
    	this.close();
    	return ListDisp;
	}
    public ArrayList<Dispositivo> ListActiveDispositivos()
    {
    	Cursor cursor = null;
    	ArrayList<Dispositivo> ListDisp = new ArrayList<Dispositivo>();
    	cursor = getReadableDatabase().query(DATABASE_NAME_DISPOSITIVOS_TABLE, null, null, null, null, null, null);
    	while(cursor.moveToNext())
    	{
    		if(cursor.getInt(cursor.getColumnIndex("active")) != 0){
    			Integer id = cursor.getInt(cursor.getColumnIndex("id"));
    			Integer idEst = cursor.getInt(cursor.getColumnIndex("idEstablecimiento"));
    			Editable name = new SpannableStringBuilder(cursor.getString(cursor.getColumnIndex("name")));
    			Editable desc = new SpannableStringBuilder(cursor.getString(cursor.getColumnIndex("description")));
    			Boolean active = cursor.getInt(cursor.getColumnIndex("active"))==1?true:false;
				ListDisp.add(new Dispositivo(id, idEst,name,desc,active));
    			//Log.d("Estblecimiento: ", cursor.getString(cursor.getColumnIndex("name")));
    		}
    	}
    	this.close();
    	return ListDisp;
	}
    public ArrayList<Dispositivo> GetDipositivosByIdEstablecimiento(Integer idEstablecimiento)
    {
    	Cursor cursor = null;
    	ArrayList<Dispositivo> ListDisp = new ArrayList<Dispositivo>();
    	cursor = getReadableDatabase().query(DATABASE_NAME_DISPOSITIVOS_TABLE, null, null, null, null, null, null);
    	while(cursor.moveToNext())
    	{
    		//if(cursor.getInt(cursor.getColumnIndex("active")) != 0){
    			if(cursor.getInt(cursor.getColumnIndex("idEstablecimiento")) == idEstablecimiento ){
    				Integer id = cursor.getInt(cursor.getColumnIndex("id"));
    				Integer idEst = cursor.getInt(cursor.getColumnIndex("idEstablecimiento"));
    				Editable name = new SpannableStringBuilder(cursor.getString(cursor.getColumnIndex("name")));
    				Editable desc = new SpannableStringBuilder(cursor.getString(cursor.getColumnIndex("description")));
    				Boolean active = cursor.getInt(cursor.getColumnIndex("active"))==1?true:false;
    				ListDisp.add(new Dispositivo(id, idEst,name,desc,active));
    				//DATABASE_NAME_DISPOSITIVOS_TABLE
    			}
    		//}
    	}
    	this.close();
    	return ListDisp;
	}
    public ArrayList<Dispositivo> GetActiveDipositivosByIdEstablecimiento(Integer idEstablecimiento)
    {
    	Cursor cursor = null;
    	ArrayList<Dispositivo> ListDisp = new ArrayList<Dispositivo>();
    	cursor = getReadableDatabase().query(DATABASE_NAME_DISPOSITIVOS_TABLE, null, null, null, null, null, null);
    	while(cursor.moveToNext())
    	{
    		if(cursor.getInt(cursor.getColumnIndex("active")) != 0){
    			if(cursor.getInt(cursor.getColumnIndex("idEstablecimiento")) == idEstablecimiento ){
    				Integer id = cursor.getInt(cursor.getColumnIndex("id"));
    				Integer idEst = cursor.getInt(cursor.getColumnIndex("idEstablecimiento"));
    				Editable name = new SpannableStringBuilder(cursor.getString(cursor.getColumnIndex("name")));
    				Editable desc = new SpannableStringBuilder(cursor.getString(cursor.getColumnIndex("description")));
    				Boolean active = cursor.getInt(cursor.getColumnIndex("active"))==1?true:false;
    				ListDisp.add(new Dispositivo(id, idEst,name,desc,active));
    				//DATABASE_NAME_DISPOSITIVOS_TABLE
    			}
    		}
    	}
    	this.close();
    	return ListDisp;
	}
    public Dispositivo GetDipositivosById(Integer idDispo)
    {
    	Cursor cursor = null;
    	Dispositivo dispositivo = null;
    	cursor = getReadableDatabase().query(DATABASE_NAME_DISPOSITIVOS_TABLE, null, null, null, null, null, null);
    	while(cursor.moveToNext())
    	{
			if(cursor.getInt(cursor.getColumnIndex("id")) == idDispo ){
				Boolean active = cursor.getInt(cursor.getColumnIndex("active")) == 1 ? true : false;
				Integer idEst = cursor.getInt(cursor.getColumnIndex("idEstablecimiento"));
				Editable name = new SpannableStringBuilder(cursor.getString(cursor.getColumnIndex("name")));
				Editable desc = new SpannableStringBuilder(cursor.getString(cursor.getColumnIndex("description")));
				dispositivo = new Dispositivo(idDispo, idEst,name,desc, active);
				//idEstablecimiento INTEGER, name VARCHAR, description TEXT, active INTEGER)";
				this.close();
				return dispositivo;
			}
    	}
    	return null;
	}
    public Boolean HayDispositivos(Integer idEstablecimiento)
    {
    	Cursor cursor = null;
    	cursor = getReadableDatabase().query(DATABASE_NAME_DISPOSITIVOS_TABLE, null, null, null, null, null, null);
    	while(cursor.moveToNext())
    	{
    		
    		if(cursor.getInt(cursor.getColumnIndex("active")) != 0){
    			if(cursor.getInt(cursor.getColumnIndex("idEstablecimiento")) == idEstablecimiento ){
    				return true;
    			}
    		}
    	}
    	this.close();
    	return false;
	}
    public void ActualizarDispositivo(Dispositivo device){
    	String strFilter = "id=" + device.getId();
    	ContentValues args = new ContentValues();
    	args.put("description", device.getDescription().toString());
    	args.put("name", device.getName().toString());
    	args.put("active", device.isActive()?1:0);
    	getReadableDatabase().update(DATABASE_NAME_DISPOSITIVOS_TABLE, args, strFilter, null);
    }
    /* FIN METODOS PARA DIPOSITIVO */
    /* METODOS PARA DETALLE RELEVAMIENTO */
    public void insertarDetalleRelevamiento(ArrayList<DetalleRelevamiento> detalleList, Integer idRelev)
    {	
    	ContentValues values = null;
    	
    	for(Integer i = 0 ; i < detalleList.size() ; i++){
    		values = new ContentValues();
    		
    		Double montoUnitario = detalleList.get(i).getMontoUnitario();
    		//Editable nameDisp = detalleList.get(i).getDispositivo().getName();
    		Integer idDisp = detalleList.get(i).getDispositivo().getId();
    		Integer vendido = detalleList.get(i).isVendido() ? 1 : 0;
    		Integer turnoManiana = detalleList.get(i).isTurnoManiana() ? 1 : 0;
    		Integer turnoTarde = detalleList.get(i).isTurnoTarde() ? 1 : 0;
    		
    		values.put("idRelevamiento", idRelev);
    		values.put("idDispositivo", idDisp);
    		values.put("montoUnitario", montoUnitario);
//    		values.put("nameDispositivo", nameDisp.toString());
    		values.put("vendido", vendido);
    		values.put("turnoManiana", turnoManiana);
    		values.put("turnoTarde", turnoTarde);
    		values.put("active", 1);
    		
    		getWritableDatabase().insert(DATABASE_NAME_DETALLES_RELEVAMIENTOS_TABLE, null, values);
    	}
    	this.close();
    }
    public ArrayList<DetalleRelevamiento> ListDetalleRelevamiento(Integer idRelev)
    {
    	//SELECT b.name FROM DetallesRelevamiento a INNER JOIN Dispositivos b ON a.idDispositivo=b.id WHERE a.idRelevamiento=1
    	
    	//private final String MY_QUERY = "SELECT b.name FROM DATABASE_NAME_DETALLES_RELEVAMIENTOS_TABLE a INNER JOIN DATABASE_NAME_DISPOSITIVOS_TABLE b ON a.idDispositivo=b.id WHERE b.idRelevamiento=?";
    	if (idRelev != null){
    		Cursor cursor = null;
    		//String cons = "SELECT * FROM " + DATABASE_NAME_DETALLES_RELEVAMIENTOS_TABLE + " a WHERE a.idRelevamiento=?";
    		//String cons = "SELECT b.name FROM " + DATABASE_NAME_DETALLES_RELEVAMIENTOS_TABLE + " a INNER JOIN " + DATABASE_NAME_DISPOSITIVOS_TABLE + " b ON a.idDispositivo = b.id WHERE b.idRelevamiento=?";
    		//cursor = getReadableDatabase().rawQuery(cons, new String[]{String.valueOf(idRelev)});    		
    	
    		cursor = getReadableDatabase().query(DATABASE_NAME_DETALLES_RELEVAMIENTOS_TABLE, null, null, null, null, null, null);    		
    	
	    	//SELECT a.id, a.idRelevamiento, b.nameDispositivo, b.idDispositivo, a.montoUnitario, a.vendido, a.turnoManiana, a.turnoTarde, a.active, b.idEstablecimiento  FROM DetallesRelevamiento a INNER JOIN Dispositivos b ON a.nameDispositivo=b.name WHERE a.idRelevamiento=1
			ArrayList<DetalleRelevamiento> ListDetalleRel = new ArrayList<DetalleRelevamiento>();
			Integer id = -1;
			Integer idDispositivo = -1;
			Double montoUnitario = (double)-1;
			Boolean vendido = false;
			Boolean turnoManiana = false;
			Boolean turnoTarde = false;
			Dispositivo dispositivo = null;
			while(cursor.moveToNext())
			{
				if(cursor.getInt(cursor.getColumnIndex("active")) != 0){
					if(cursor.getInt(cursor.getColumnIndex("idRelevamiento")) == idRelev){
						id = cursor.getInt(cursor.getColumnIndex("id"));
						idDispositivo = cursor.getInt(cursor.getColumnIndex("idDispositivo"));
						montoUnitario = cursor.getDouble(cursor.getColumnIndex("montoUnitario"));
						vendido = cursor.getInt(cursor.getColumnIndex("vendido")) == 1 ? true : false;
						turnoManiana = cursor.getInt(cursor.getColumnIndex("turnoManiana")) == 1 ? true : false;
						turnoTarde = cursor.getInt(cursor.getColumnIndex("turnoTarde")) == 1 ? true : false;
						dispositivo = GetDipositivosById(idDispositivo);
						ListDetalleRel.add(new DetalleRelevamiento(id, idRelev, idDispositivo, montoUnitario, vendido, turnoManiana, turnoTarde, dispositivo));
					}
				}
			}
			this.close();
			return ListDetalleRel;
    	}
    	return null;
    }
    /* FIN METODOS PARA DETALLE RELEVAMIENTO */
    /* METODOS PARA RELEVAMIENTO */
    public ArrayList<Relevamiento> ListRelevamientos(Integer idUsuario){
    	// listar con id de user
    	Cursor cursor = null;
    	ArrayList<Relevamiento> ListRelev = new ArrayList<Relevamiento>();
    	cursor = getReadableDatabase().query(DATABASE_NAME_RELEVAMIENTOS_TABLE, null, null, null, null, null, null);
    	while(cursor.moveToNext())
    	{
    		if(cursor.getInt(cursor.getColumnIndex("active")) != 0){
    			if(cursor.getInt(cursor.getColumnIndex("idUser")) == idUsuario){
    			Integer id = cursor.getInt(cursor.getColumnIndex("id"));
    			//Integer idUser = cursor.getInt(cursor.getColumnIndex("idUser"));
				Editable name = new SpannableStringBuilder(cursor.getString(cursor.getColumnIndex("name")));
				Editable dateUpdated = new SpannableStringBuilder(cursor.getString(cursor.getColumnIndex("dateUpdated")));
				Double montoTotal = cursor.getDouble(cursor.getColumnIndex("montoTotal"));
				ListRelev.add(new Relevamiento(id, idUsuario, dateUpdated, montoTotal, name));
				//Log.d("Estblecimiento: ", cursor.getString(cursor.getColumnIndex("name")));
    			//idUser INTEGER, name VARCHAR, dateUpdated NUMERIC, montoTotal REAL, active INTEGER
    			}
    		}
    	}
    	this.close();
    	return ListRelev;
    }
    public Integer insertarRelevamiento(Relevamiento relev)
    {	
    	ContentValues values = new ContentValues();
    	
    	double aux = (double)0;
    	for(int i = 0 ; i < relev.getDetalleRelevamiento().size() ; i++){
    		aux += relev.getDetalleRelevamiento().get(i).getMontoUnitario();
    	}
    	relev.setMontoTotal(aux);
    	
    	Editable name = relev.getName();
    	String dateUpdated = getCurrentTimeStamp();
    	Integer idUser = relev.getIdUser();
    	Double montoTotal = relev.getMontoTotal();
    	
    	values.put("name", name.toString());
    	values.put("dateUpdated", dateUpdated);
    	values.put("idUser", idUser);
    	values.put("montoTotal", montoTotal);
    	values.put("active", 1);
    	
    	getWritableDatabase().insert(DATABASE_NAME_RELEVAMIENTOS_TABLE, null, values);
    	this.close();
    	return getIdRelevamiento(name.toString());
    }
    public Integer getIdRelevamiento(String nameRelevamiento){
    	Cursor cursor = null;
    	
    	cursor = getReadableDatabase().query(DATABASE_NAME_RELEVAMIENTOS_TABLE, null, null, null, null, null, null);
    	   	
    	//String relevamiento = nameRelevamiento.toString();
    	
    	while(cursor.moveToNext()){
    		if(nameRelevamiento.equals(cursor.getString(cursor.getColumnIndex("name")))){
    			return cursor.getInt(cursor.getColumnIndex("id"));
    		}
    	}
    	return -1;
    }
    public Boolean existeRelevamiento(Editable name){
    	int flag = 0;
    	Cursor cursor = null;
    	cursor = getReadableDatabase().query(DATABASE_NAME_RELEVAMIENTOS_TABLE, null, null, null, null, null, null);
    	
    	while(cursor.moveToNext()){
    		if(name.toString().equals(cursor.getString(cursor.getColumnIndex("name")))){
    			flag = 1;
    		}
    	}
    	this.close();
    	if(flag == 1){
    		return true;
    	}else{
    		return false;
    	}
	}
    public Boolean tieneRelevamientos(Integer idUser){
    	int flag = 0;
    	Cursor cursor = null;
    	cursor = getReadableDatabase().query(DATABASE_NAME_RELEVAMIENTOS_TABLE, null, null, null, null, null, null);
    	
    	while(cursor.moveToNext()){
    		if(idUser.equals(cursor.getInt(cursor.getColumnIndex("idUser")))){
    			flag = 1;
    		}
    	}
    	this.close();
    	if(flag == 1){
    		return true;
    	}else{
    		return false;
    	}
	}
    /* FIN METODOS PARA RELEVAMIENTO */
    /* Metodos auxiliares*/
    public static String getCurrentTimeStamp() {
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//dd/MM/yyyy
        Date now = new Date();
        String strDate = sdfDate.format(now);
        return strDate;
    }
}